﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;

namespace KTX.AN
{
    public partial class FrmUser : Form
    {
        SqlConnection conn;
        SqlCommand cmd;
        SqlDataAdapter da;
        SqlDataReader reader;
        DataTable dt;
        Configuration config;
        String strCmd;

        public FrmUser()
        {
            InitializeComponent();

            config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            var strConn = config.ConnectionStrings.ConnectionStrings[1].ConnectionString;

            conn = new SqlConnection(strConn);
            cmd = new SqlCommand();
        }

        private void frmUser_Load(object sender, EventArgs e)
        {
            loadPrivilege();
            loadUser();
            if (gvUser.RowCount > 0)
            {
                txtID.Text = gvUser.SelectedRows[0].Cells[0].Value.ToString();
                txtPass.Text = gvUser.SelectedRows[0].Cells[1].Value.ToString();
            }
        }

        private void loadPrivilege()
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();

            strCmd = cmd.CommandText = "SELECT * FROM [tb_Privilege]";
            da = new SqlDataAdapter(strCmd, conn);
            dt = new DataTable();
            da.Fill(dt);
            cbxRole.DataSource = dt;
            cbxRole.DisplayMember = "Name";
            cbxRole.ValueMember = "Id";
        }

        private void loadUser()
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();

            strCmd = cmd.CommandText = "SELECT u.Id,Pass,Name FROM [tb_User] u,[tb_Privilege] p WHERE u.Role=p.ID";
            da = new SqlDataAdapter(strCmd, conn);
            dt = new DataTable();
            da.Fill(dt);
            gvUser.DataSource = dt;
            gvUser.Columns[0].HeaderText = "Định danh";
            gvUser.Columns[1].Visible = false;
            gvUser.Columns[2].HeaderText = "Quyền";
            if (gvUser.RowCount > 0)
            {
                cbxRole.SelectedItem = gvUser.SelectedRows[0].Cells[2].Value.ToString();
                txtID.Text = gvUser.SelectedRows[0].Cells[0].Value.ToString();
                txtPass.Text = gvUser.SelectedRows[0].Cells[1].Value.ToString();
            }
        }

        private void gvUser_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (gvUser.RowCount > 0)
            {
                cbxRole.SelectedItem = gvUser.SelectedRows[0].Cells[2].Value.ToString();
                txtID.Text = gvUser.SelectedRows[0].Cells[0].Value.ToString();
                txtPass.Text = gvUser.SelectedRows[0].Cells[1].Value.ToString();
            }
        }

        private bool checkExist(string Id)
        {
            cmd = new SqlCommand("SELECT * FROM [tb_User] WHERE Id='" + Id + "'", conn);
            reader = cmd.ExecuteReader();
            if (reader.Read())
            {
                reader.Close();
                return true;
            }
            reader.Close();
            return false;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (btnAdd.Text.Equals("&Thêm"))
            {
                btnAdd.Text = "&Lưu lại";
                btnEdit.Enabled = false;
                btnDelete.Enabled = false;
                txtID.Enabled = true;
                txtPass.Enabled = true;
                txtID.Text = "";
                txtPass.Text = "";
                txtID.Focus();
            }
            else
            {
                if (txtID.Text == "" || txtPass.Text == "")
                {
                    MessageBox.Show("Phải điền đầy đủ thông tin", "Yêu cầu", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else if (checkExist(txtID.Text))
                {
                    MessageBox.Show("Định danh này đã tồn tại", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    cmd = new SqlCommand("INSERT INTO [tb_User] VALUES(@id,@pass,@role)", conn);
                    cmd.Parameters.AddWithValue("@id", txtID.Text);
                    cmd.Parameters.AddWithValue("@pass", txtPass.Text);
                    cmd.Parameters.AddWithValue("@role", cbxRole.SelectedValue);
                    if (cmd.ExecuteNonQuery() > 0)
                    {
                        loadUser();
                        btnAdd.Text = "&Thêm";
                        btnEdit.Enabled = true;
                        btnDelete.Enabled = true;
                        txtID.Enabled = false;
                        txtPass.Enabled = false;
                    }
                }
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (btnEdit.Text.Equals("&Sửa"))
            {
                btnEdit.Text = "&Lưu lại";
                btnAdd.Enabled = false;
                btnDelete.Enabled = false;
                txtID.Enabled = false;
                txtPass.Enabled = true;
                txtPass.Focus();
            }
            else
            {
                cmd = new SqlCommand("UPDATE [tb_User] SET Pass=@pass,Role=@role WHERE Id=@id", conn);
                cmd.Parameters.AddWithValue("@id", txtID.Text);
                cmd.Parameters.AddWithValue("@pass", txtPass.Text);
                cmd.Parameters.AddWithValue("@role", cbxRole.SelectedValue);
                if (cmd.ExecuteNonQuery() > 0)
                {
                    loadUser();
                    btnEdit.Text = "&Sửa";
                    btnAdd.Enabled = true;
                    btnDelete.Enabled = true;
                    txtID.Enabled = false;
                    txtPass.Enabled = false;
                }
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Bạn chắc có muốn xóa không ?", "Xác nhận", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                cmd = new SqlCommand("DELETE FROM [tb_User] WHERE Id=@id", conn);
                cmd.Parameters.AddWithValue("@id", txtID.Text);
                if (cmd.ExecuteNonQuery() > 0)
                {
                    loadUser();
                }
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            loadUser();
            btnAdd.Enabled = true;
            btnEdit.Enabled = true;
            btnDelete.Enabled = true;
            btnAdd.Text = "&Thêm";
            btnEdit.Text = "&Sửa";
            btnDelete.Text = "&Xóa";
            txtID.Enabled = false;
            txtPass.Enabled = false;
        }

        private void txtSearch_MouseDown(object sender, MouseEventArgs e)
        {
            txtSearch.Text = "";
        }

        private void searchUser(string id)
        {
            da = new SqlDataAdapter("SELECT u.Id,Pass,Name FROM [tb_User] u,[tb_Privilege] p WHERE u.Role=p.ID and u.Id like '%" + id + "%'", conn);
            dt = new DataTable();
            da.Fill(dt);
            gvUser.DataSource = dt;
        }

        private void txtSearch_TextChanged(object sender, EventArgs e)
        {
            try
            {
                searchUser(txtSearch.Text);
            }
            catch (Exception)
            {
                txtSearch.Text = "";
            }
        }
    }
}